﻿using System.Net;
using FluentPS.Services;
using Microsoft.SharePoint.Administration.Claims;


namespace FluentPS.Impersonation
{
    public class ImpersonationHelper
    {
        private const string HeaderPjAuth = "PjAuth";
        public const string HeaderForwardedFrom = "ForwardedFrom";
        internal const string VtiBinPrefix = "/_vti_bin/psi/";

        public static string GetClaim(string userAccount)
        {
            string claimsRepresentation = userAccount;
            if (!SPClaimProviderManager.IsEncodedClaim(userAccount))
            {
                SPClaim claim = SPClaimProviderManager.Local.ConvertIdentifierToClaim(userAccount,
                                                                                      SPIdentifierTypes.
                                                                                          WindowsSamAccountName);
                claimsRepresentation = claim.ToEncodedString();
            }
            return claimsRepresentation;
        }

        public static void PrepareWebRequest(WebRequest webRequest, IPsiContextService psiContextService)
        {
            var context = psiContextService.GetImpersonationContext();
            if (context != null)
            {
                int servNameIndex = webRequest.RequestUri.AbsolutePath.LastIndexOf("/") + 1;
                string forwardedFrom = VtiBinPrefix + webRequest.RequestUri.AbsolutePath.Substring(servNameIndex, webRequest.RequestUri.AbsolutePath.Length - servNameIndex);
                webRequest.UseDefaultCredentials = true;
                webRequest.PreAuthenticate = true;

                webRequest.Headers.Add(HeaderPjAuth, context.GetImpersonationHeader());
                webRequest.Headers.Add(HeaderForwardedFrom, forwardedFrom);                
                webRequest.ConnectionGroupName = context.SiteId.ToString();

                if (webRequest is HttpWebRequest)
                    ((HttpWebRequest)webRequest).UnsafeAuthenticatedConnectionSharing = true;
            }
        }
    }
}
